# -*- coding: utf-8 -*-

import optparse
import socket
from threading import *

screen_lock = Semaphore(value=1)


def conn_scan(tgt_host, tgt_port):
    try:
        conn_skt = socket(AF_INET, SOCK_STREAM)
        conn_skt.connect((tgt_host, tgt_port))
        conn_skt.send('hello world\r\n')
        results = conn_skt.recv(100)
        screen_lock.acquire()
        print('[+] %d/tcp open'.format(tgt_port))
        print('[+] ' + str(results))
    except:
        screen_lock.acquire()
        print('[-] %d/tcp closed'.format(tgt_port))
    finally:
        screen_lock.release()
        conn_skt.close()


def port_scan(tgt_host, tgt_ports):
    try:
        tgt_ip = socket.gethostbyname(tgt_host)
    except:
        print('[-] Cannot resolve {0}: Unkonwn host'.format(tgt_host))
        return None

    try:
        tgt_name = socket.gethostbyaddr(tgt_ip)
        print('\n[+] Scan Results for: {0}'.format(tgt_name[0]))
    except:
        print('\n[+] Scan Results for: {0}'.format(tgt_ip))

    setdefaulttimeout(1)
    for tgt_port in tgt_ports:
        t = Thread(target=conn_scan, args=(tgt_host, int(tgt_port)))
        t.start()
